//
//  FileViewController.m
//  OurLottery
//
//  Created by hubing on 2018/9/4.
//  Copyright © 2018年 hl. All rights reserved.
//

#import "FileViewController.h"
#import "UpdateViewController.h"
#import "VideoPlayerController.h"
#import "ChatImageBrowserView.h"
//#import "ImageBrowser.h"
#import "NSString+Common.h"
#import "ZipArchive.h"
#import "AuthCodeLabel.h"
//#import <Speech/Speech.h>
#import "AudioTransferTool.h"
#import <StoreKit/StoreKit.h>
#import "QRcodeRecognitionView.h"
#import "TenMillionTool.h"

@interface FileViewController ()<UITableViewDelegate, UITableViewDataSource,UITextViewDelegate,SSZipArchiveDelegate>
/* fileTableView */
@property (nonatomic, weak) UITableView *fileTableView;
/* fileArray */
@property (nonatomic, strong) NSMutableArray *fileArray;

@property (nonatomic, strong) UIView *noDataView;

@property (nonatomic, strong) UITextView *tv;

@property (nonatomic, strong) NSString *tempStr;

@property (nonatomic, strong) UIButton *recordBtn;

@property (nonatomic,strong) QRcodeRecognitionView *recognitionView;

// 首页显示 音乐，读书（后期接入电子书功能。） 古诗（后期完善故事检索功能。以及页面问题），美图（后期完善网络图片预览功能）

// 身份证 照片保存功能。
//



@end

@implementation FileViewController

-(UIView *)noDataView{
    if (!_noDataView) {
        _noDataView = [[UIView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_noDataView];
        
        UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nofile"]];
        image.contentMode = UIViewContentModeScaleAspectFit;
        [_noDataView addSubview:image];
        [image sizeWith:CGSizeMake(ScreenWidth/3, ScreenHeight/3)];
        [image layoutParentHorizontalCenter];
        [image alignParentTopWithMargin:ScreenWidth/4];
        DebugLog(@"%@",[TenMillionTool getRandomRedBall]);
        
        
        AuthCodeLabel *label = [[AuthCodeLabel alloc]init];
        [label setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_noDataView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_noDataView);
            make.width.mas_equalTo(150);
            make.height.mas_equalTo(30);
        }];
        
        [label setTitle:@"Clear" forState:UIControlStateNormal];
        [label addTarget:self action:@selector(toWebView) forControlEvents:UIControlEventTouchUpInside];
        
        DebugLog(@"~~~~~~%@",[self getTopicFromTitle:@""]);
        
        UIButton *refresh = [UIButton buttonWithType:UIButtonTypeCustom];
        [refresh setTitle:@"无法连接网络，请点击刷新" forState:UIControlStateNormal];
        [refresh setTitleColor:RGBOF(0x6C9AF3) forState:UIControlStateNormal];
        [refresh addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataView addSubview:refresh];
        
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        UIColor *color2 = [UIColor clearColor];
        UIColor *color3 = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        gradientLayer.colors = @[(__bridge id)color2.CGColor,(__bridge id)color3.CGColor];
        gradientLayer.locations = @[@(0.5f),@(1.0f)];
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(0, 1.0);
        
        gradientLayer.frame = CGRectMake(0, SCREEN_HEIGHT-180, ScreenWidth, 180);
        [_noDataView.layer addSublayer:gradientLayer];
        
        self.recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.recordBtn setTitle:@"点击识别二维码" forState:UIControlStateNormal];
//        [self.recordBtn setTitle:@"松开开始识别" forState:UIControlStateHighlighted];
        [self.recordBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//        [self.recordBtn addTarget:self action:@selector(recordButtonTouchDown) forControlEvents:UIControlEventTouchDown];
//        [self.recordBtn addTarget:self action:@selector(recordButtonTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
        [self.recordBtn addTarget:self action:@selector(recordButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
//        [self.recordBtn addTarget:self action:@selector(recordDragOutside) forControlEvents:UIControlEventTouchDragExit];
//        [self.recordBtn addTarget:self action:@selector(recordDragInside) forControlEvents:UIControlEventTouchDragEnter];
        self.recordBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        self.recordBtn.layer.borderWidth = 1;
        self.recordBtn.layer.cornerRadius = 40/2;
        self.recordBtn.layer.masksToBounds = YES;
        [_noDataView addSubview:self.recordBtn];
        [self.recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noDataView);
            make.centerY.equalTo(_noDataView).offset(100);
            make.width.mas_equalTo(150);
            make.height.mas_equalTo(40);
        }];
        
        _tv = [[UITextView alloc]init];
        _tv.textColor = [UIColor blackColor];
        _tv.keyboardType = 0;
        _tv.hidden = YES;
        [_noDataView addSubview:_tv];   
        [_tv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(5);
            make.right.mas_equalTo(-5);
            make.top.mas_equalTo(SafeAreaTopHeight);
            make.height.mas_equalTo(200);
        }];
        [refresh sizeToFit];

        _noDataView.backgroundColor = RGBOF(0xF0EEEB);

        _noDataView.hidden = YES;
    }
    return _noDataView;
}

-(NSArray *)getTopicFromTitle:(NSString *)title
{
    title = @"测试视频#话题2 #话题1 #话题爱了2 #话题测试 #我是大漂亮 #我是小漂亮";
    NSMutableArray *topicArr = [NSMutableArray array];
    NSArray *temp1 = [title componentsSeparatedByString:@" "];
    for (NSString *tempStr in temp1) {
        NSString *temp2 = [tempStr componentsSeparatedByString:@"#"].lastObject;
        temp2 = [NSString stringWithFormat:@"#%@",temp2];
        [topicArr addObject:temp2];
    }
    return [topicArr copy];
}

-(void)recordButtonTouchDown
{
    [self startVoiceRecigizer];
}
-(void)recordButtonTouchUpOutside
{
    [self.recordBtn setTitle:@"按住说话" forState:UIControlStateNormal];
    [self stopVoiceRecigizer];
}
-(void)recordButtonTouchUpInside
{
//    [self swipQRCode];
    // 如果存在 ，就移除，重新加载
//    if (_recognitionView) {
//        [_recognitionView removeFromSuperview];
//    }
//    NSString *url2 = @"http://dr.careate.cn/i.html";  // 可以
//    _recognitionView = [[QRcodeRecognitionView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height) andUrlstr:url2];
//    _recognitionView.recognitionBlock = ^(NSString * _Nonnull codeStr) {
//        [HUDHelper alert:codeStr];
//    };
//    [self.view addSubview:_recognitionView];
    
    NSString *urlStr = @"careate://szrmb/MedicalcheckupPaymentPage?orderNo=abcdeftsdfasd&trdDtTm=202209011721&procSts=0001&procInf=paysuccess";
    NSURL *url = [NSURL URLWithString:urlStr];
    [[UIApplication sharedApplication]openURL:url options:nil completionHandler:^(BOOL success) {
            
    }];
    
    
}
-(void)recordDragOutside
{
    [self.recordBtn setTitle:@"松开开始识别" forState:UIControlStateNormal];
}

-(void)recordDragInside
{
    [self.recordBtn setTitle:@"按住说话" forState:UIControlStateNormal];
}

-(NSArray *)getPhoneNumberFormString:(NSString *)aString
{
    NSMutableArray *phoneNumbers = [NSMutableArray array];
    if (!aString || aString.length == 0) {
        return [phoneNumbers copy];
    }
    NSString *regulaStr = @"\\d{3,4}[- ]?\\d{7,8}";
    NSRange stringRange = NSMakeRange(0, aString.length);
    
    NSError *error;
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:aString];
    NSRegularExpression *regexps = [NSRegularExpression regularExpressionWithPattern:regulaStr options:0 error:&error];
    NSInteger matches = [regexps numberOfMatchesInString:aString options:0 range:NSMakeRange(0, aString.length)];
    if (matches <= 0)
    {
        return [phoneNumbers copy];
    }
    
    if (!error && regexps != nil) {
        [regexps enumerateMatchesInString:aString options:0 range:stringRange usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            NSRange phoneRange = result.range;
            NSAttributedString *phoneNumber = [str attributedSubstringFromRange:phoneRange];
            [phoneNumbers addObject:phoneNumber.string];
        }];
    }
    return [phoneNumbers copy];
}

-(void)startVoiceRecigizer
{
    [[AudioTransferTool sharedTool]startVoiceRecigizer];
}

-(void)stopVoiceRecigizer
{
    [[AudioTransferTool sharedTool]stopVoiceRecigizerCompleteBlock:^(NSString * _Nonnull result) {
        DebugLog(@"block出来的：%@",result);
        self.tv.text = [self.tv.text stringByAppendingFormat:@"%@",result];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.tv resignFirstResponder];
}

-(void)toWebView
{
    self.tv.text = @"";
}

-(void)refresh:(UIButton *)sender{
    NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", @"1005512045"];
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:str]];
}


- (NSMutableArray<NSString *> *)fileArray {
    if (!_fileArray) {
        _fileArray = [NSMutableArray array];
    }
    return _fileArray;
}

- (UITableView *)fileTableView {
    if (!_fileTableView) {
        UITableView *tv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        
        // 设置代理
        tv.delegate = self;
        // 设置数据源
        tv.dataSource = self;
        // 清除表格底部多余的cell
        tv.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        
        [self.view addSubview:tv];
        _fileTableView = tv;
    }
    return _fileTableView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.noDataView) {
        self.noDataView.hidden = NO;
    }
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIDevice currentDevice].proximityMonitoringEnabled = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的文件";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"chuansong"] style:UIBarButtonItemStylePlain target:self action:@selector(uploadFile:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Qrcode"] style:UIBarButtonItemStylePlain target:self action:@selector(swipQRCode)];
    self.navigationItem.leftBarButtonItem = leftItem;
}


-(void)swipQRCode
{
    MyWebViewController *webvc = [[MyWebViewController alloc]initWithTitle:@"www.baidu.com" andUrl:@"www.baidu.com"];
    webvc.recogizerBlock = ^(NSString *codeStr) {
        NSString *print = [NSString stringWithFormat:@"二维码内容：%@",codeStr];
        [HUDHelper alert:print];
    };
    [self presentViewController:webvc animated:YES completion:nil];
}

-(void)aesEncryTest
{
    QRCodeReaderViewController *reader = [[QRCodeReaderViewController alloc]init];
    [reader setCompletionWithBlock:^(NSString *resultAsString){
        DebugLog(@"识别出来的字符：%@",resultAsString);
    }];
    NSString *str1 = @"abcdefg";
    NSString *str2 = @"bacefgd";

    NSLog(@"str1:%@ hash==%lu,str2:%@ hash==%lu,",str1,(unsigned long)[str1 hash],str2,(unsigned long)[str2 hash]);

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSDictionary *saveInfo = @{@"addTime":[TimeTool nowTimeStr3],@"ChoiceDescription":@"阿世纪东方i啊圣诞快乐放假啊四栋 啊四栋减肥i我去哦皮肤上的疯狂了时间的离开"};
    [param setValue:saveInfo forKey:@"saveInfo"];
    
    
    NSString *jsonString = [QHCommonTool returnJsonstringwithObject:param];
    
    NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];
    
    NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];

    NSString * key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];

    NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];

    
    NSString *aseStr = [NSString AES128Encrypt:upperUnicode withKey:result22];
    
    NSString *desStr = [NSString AES128Decrypt:aseStr withKey:result22];
    
    NSLog(@"%@",@"12345");
    NSLog(@"aseStr:%@ \n desStr:%@",aseStr,desStr);
}

-(void)unzipTest
{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",@"main.js.zip"] ofType:nil];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",@"ZipFile/"]];

    NSString *UnZipPassWordStr = @"careate2020!zip";

    NSError *unzipError = nil;
    BOOL ZipResult = [SSZipArchive unzipFileAtPath:filePath toDestination:dstPath preserveAttributes:YES overwrite:YES password:UnZipPassWordStr error:&unzipError delegate:self];
    if (ZipResult) {
        NSLog(@"%@解压成功",@"main.js.zip");
        NSLog(@"from:%@,to:%@",filePath,dstPath);
    }else{
        NSLog(@"%@解压失败：%@",@"main.js.zip",unzipError.userInfo[NSLocalizedDescriptionKey]);
    }
}

+(NSArray *)subString:(NSString *)atext ToFitLength:(NSUInteger )length
{
    NSMutableArray *strArr = [NSMutableArray array];
    if (atext.length > length)
    {
        NSString *tempStr = [atext substringWithRange:NSMakeRange(0, length)];
        [strArr addObject:tempStr];
        atext = [atext substringFromIndex:length];
        [strArr addObjectsFromArray:[self subString:atext ToFitLength:length]];
    }
    else
    {
        [strArr addObject:atext];
    }
    return [strArr mutableCopy];
}

-(NSString *)returnJsonstringwithObject:(id)aObject{
    NSString *  jsonStr = @"";
    if ([aObject isKindOfClass:[NSDictionary class]]) {
        NSString *  jsonStr = [@"" stringByAppendingString:@"{"];
        NSDictionary *tempDic = (NSDictionary *)aObject;
        NSArray *tempKeys = [tempDic allKeys];
        NSArray *keys = [tempKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        for (NSString *key in keys) {
            jsonStr = [jsonStr stringByAppendingFormat:@"%@:%@,",key,[self returnJsonstringwithObject:[tempDic objectForKey:key]]];
        }
         jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
         jsonStr =[jsonStr stringByAppendingString:@"}"];
        return jsonStr;
    }else if ([aObject isKindOfClass:[NSArray class]]){
        jsonStr =[jsonStr stringByAppendingString:@"["];
        NSArray *tempArr = (NSArray *)aObject;
        for (id object in tempArr) {
            jsonStr = [jsonStr stringByAppendingFormat:@"%@,",[self returnJsonstringwithObject:object]];
        }
        jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
        jsonStr= [jsonStr stringByAppendingString:@"]"];
        return jsonStr;
    }else{
        jsonStr = [jsonStr stringByAppendingFormat:@"%@",aObject];
        return  jsonStr;
    }
    return jsonStr;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSLog(@"%@",text);
    return YES;
}

-(void)uploadFile:(UIBarButtonItem *)item{
    // 评价2
    SKStoreProductViewController *storeProductViewController = [SKStoreProductViewController new];
    [storeProductViewController loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier:@"1005512045"} completionBlock:^(BOOL result, NSError * _Nullable error) {
        if (error)
            DebugLog(@"error %@ with userInfo %@",error,[error userInfo]);
        else
            [self presentViewController:storeProductViewController animated:YES completion:nil];
    }];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.text = self.fileArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",self.fileArray[indexPath.row]);
    NSString *fileName = self.fileArray[indexPath.row];
    NSString *fileType = [[fileName componentsSeparatedByString:@"."]lastObject];
    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    if ([fileType isEqualToString:@"mp4"]) {
        NSDictionary *dict = @{@"url":url.absoluteString,@"name":fileName,@"cover_url":@""};
        VideoPlayerController *vc = [[VideoPlayerController alloc]initWithData:dict];
        vc.hidesBottomBarWhenPushed = YES;
        [self presentViewController:vc animated:NO completion:nil];
    }else if ([fileType isEqualToString:@"jpg"]||[fileType isEqualToString:@"png"]){
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        ChatImageBrowserView *view = [[ChatImageBrowserView alloc]initWiththumbnail:image fromRect:self.view.bounds];
        UIView *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:view];
    }else if ([fileType isEqualToString:@"pdf"]||[fileType isEqualToString:@"doc"]||[fileType isEqualToString:@"docx"]||[fileType isEqualToString:@"xls"]||[fileType isEqualToString:@"xlsx"]){
        MyWebViewController *webvc = [[MyWebViewController alloc]initWithTitle:fileName andUrl:url.absoluteString];
        webvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webvc animated:YES];
    }else if ([fileType isEqualToString:@"txt"]){
        
        MyWebViewController *webvc = [[MyWebViewController alloc]initWithTitle:fileName andUrl:filePath];
        webvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webvc animated:YES];
    }
}

@end
